using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;

namespace Catchbase.TestTools
{
    public static class Reflections
    {
        public static Object CreateInstance(this Type type, params Object[] parameters)
        {
            return Activator.CreateInstance(type, parameters);
        }

        public static T CreateInstance<T>(this Type type, params Object[] parameters)
        {
            return (T) type.CreateInstance(parameters);
        }

        public static IEnumerable<Type> CtorParams(this Type type)
        {
            return type.CtorPublicMax().GetParameters().Select(p => p.ParameterType);
        }

        private static ConstructorInfo CtorPublicMax(this Type type)
        {
            List<ConstructorInfo> ctors = type.CtorsPublic().ToList();
            Debug.Assert(ctors.Any(), string.Format("{0} must have at least one public ctor.", type.Name));
            return ctors.OrderByDescending(c => c.GetParameters().Count()).First();
        }

        private static IEnumerable<ConstructorInfo> CtorsPublic(this Type type)
        {
            return type.GetConstructors(BindingFlags.Public | BindingFlags.Instance);
        }
    }
}